package com.situ.b2c.util;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * 
 * #带参 的构造函数，当用户需要得到工具类实例的时候，强制调用此构造函数，将request传入
 * # 在此处，解析request中的表单数据，将其中的文本数据解析成一个Map<fieldName,fieldVal>
 *
 *@param request
 */
public class FileUploadUtil {
	//表单文本信息数据
	private Map<String, String> fieldMap = new HashMap<String, String>();
	//
	private Map<String, FileItem> multipartMap = new HashMap<String, FileItem>();
	
	public FileUploadUtil(HttpServletRequest request) {
		
		//判断当前是否是二进制流提交
				boolean isMultipart = ServletFileUpload.isMultipartContent(request);
				if (isMultipart) {
					//创建一个新的ServletFileUpload实例
					DiskFileItemFactory factory = new DiskFileItemFactory();
					ServletFileUpload upload = new ServletFileUpload(factory);
					try {
						//解析request中的表单数据
						List<FileItem> fileItemList = upload.parseRequest(request);
						//判断表单中的数据有值
						if (fileItemList != null && ! fileItemList.isEmpty()) {
							for (FileItem fileItem : fileItemList) {
								//判断如果是文本Item
								boolean isFormField = fileItem.isFormField();
								if (isFormField) {
									//将fieldName和fieldVal 分别赋值给文本数据Map
									String fieldName = fileItem.getFieldName();
									String fieldVal = fileItem.getString("utf-8");
									fieldMap.put(fieldName, fieldVal);
								}else {  //判断是二进制的Item
									String fieldName = fileItem.getFieldName();
										multipartMap.put(fieldName, fileItem);
						
								}
							}
						}
					} catch (FileUploadException e) {
						e.printStackTrace();
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
				}
	}
		
	public String getParameter(String fieldName) {
		
		return fieldMap.get(fieldName);
		
	}
	
	public FileItem getBinaryData(String fieldName) {
		
		return multipartMap.get(fieldName);
		
	}
	
	
	
}
